<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="id"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效列 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-circle-check icon_style"
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i
            class="el-icon-circle-close icon_style"
            style="color: red"
            v-else
          ></i>
        </template>
        <!-- 排序列 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            type="success"
            >二级</el-tag
          >
          <el-tag size="mini" v-else type="warning">三级</el-tag>
        </template>
        <!-- 操作列 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editCate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[5, 8, 10, 15]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级名称：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCates">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editRoleDialogClosed"
    >
      <!-- 编辑分类表单 -->
      <el-form
        :model="shopList"
        :rules="addCateFormRules"
        ref="shopListRef"
        label-width="100px"
      >
        <el-form-item label="分类id：" prop="cat_id">
          <el-input v-model="shopList.cat_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="shopList.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //查询参数条件每页展示条数以及展示第几页
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 8,
      },
      //商品分类列表
      cateList: [],
      //总数据条数
      total: 0,
      //为tree-table指定列名称定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          //声明当前列为模板列
          type: 'template',
          //模板列名称
          template: 'isok',
        },
        {
          //每个对象都是一列
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
        },
      ],
      addCateDialogVisible: false,
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        //分类等级默认要添加的是一级分类
        cat_level: 0,
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      //父级分类的列表数据
      parentCateList: [],
      //选中的父级分类id数组
      selectedKeys: [],
      shopList: {},
      editCateDialogVisible: false,
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: response } = await this.$http.get('categories', {
        params: this.querInfo,
      });
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.cateList = response.data.result;
      this.total = response.data.total;
    },
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.querInfo.pagenum = newPage;
      this.getCateList();
    },
    setRoleDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //展示添加分类对话框
    addCate() {
      //先获取父级分类列表再展示对话框
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类的数据列表
    async getParentCateList() {
      const { data: response } = await this.$http.get('categories', {
        params: { type: 2 },
      });
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.parentCateList = response.data;
    },
    //Cascader选择项发生变化触发调用
    parentCateChanged() {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    addCates() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: response } = await this.$http.post(
          'categories',
          this.addCateForm
        );
        if (response.meta.status !== 201)
          return this.$message({
            message: response.meta.msg,
            type: 'error',
            center: true,
          });
        this.$message({
          message: response.meta.msg,
          type: 'success',
          center: true,
        });
        this.getCateList();
        this.addCateDialogVisible = false;
      });
    },
    async removeCate(id) {
      const confirmResult = await this.$confirm('确认永久删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') return;
      const { data: response } = await this.$http.delete('categories/' + id);
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.getCateList();
    },
    async editCate(id) {
      const { data: response } = await this.$http.get('categories/' + id);
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
      this.shopList = response.data;
      this.editCateDialogVisible = true;
    },
    editRoleDialogClosed() {
      this.$refs.shopListRef.resetFields();
    },
    async editOk() {
      const { data: response } = await this.$http.put(
        'categories/' + this.shopList.cat_id,
        {
          cat_name: this.shopList.cat_name,
        }
      );
      if (response.meta.status !== 200)
        return this.$message({
          message: response.meta.msg,
          type: 'error',
          center: true,
        });
        this.$message({
          message: response.meta.msg,
          type: 'success',
          center: true,
        });
        this.getCateList()
        this.editCateDialogVisible = false
    },
  },
};
</script>

<style scoped>
.icon_style {
  font-size: 18px;
  vertical-align: middle;
}

.treeTable {
  margin: 15px 0;
}

.el-cascader {
  width: 100%;
}
</style>